/**
 * Copyright 2008-2009 HAN.BIFANG
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */
package han.bifang.gwt.client.service.content;

import han.bifang.gwt.client.common.Content;
import han.bifang.gwt.client.common.GwtContext;
import han.bifang.gwt.client.common.PrivilegChecker;
import han.bifang.gwt.client.common.RequestObject;
import han.bifang.gwt.client.common.ResponseObject;
import han.bifang.gwt.client.common.entity.Role;
import han.bifang.gwt.client.common.entity.User;
import han.bifang.gwt.client.common.util.StringUtils;
import han.bifang.gwt.client.communicate.BifangGWTServiceAsync;
import han.bifang.gwt.client.sec.CustomCheckBox;
import han.bifang.gwt.client.service.ServiceMessages;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.ui.HTMLTable.CellFormatter;
import com.google.gwt.user.client.ui.HTMLTable.ColumnFormatter;

/**
 * 
 * @Author Kent
 */
public class ServiceRoleRefContent extends Content implements RoleSearcher {

	private ServiceMessages cons = null;

	private BifangGWTServiceAsync service = null;

	private GwtContext context = null;
	private VerticalPanel panel;

	private String resourceId;

	private SimplePanel tablePanel;
	private CustomCheckBox[] checks;
	private ArrayList<Role> g, tmp;

	private boolean loaded;

	private AsyncCallback<ResponseObject> cb = new AsyncCallback<ResponseObject>() {
		public void onSuccess(ResponseObject res) {
			String code = res.getCode();
			if (!code.equals("0")) {
				Window.alert("There was an error: " + res.getMsg());
				return;
			}
			for (CustomCheckBox check : checks) {
				if (check.isChecked()) {
					Role gr = (Role) check.getProperties();
					g.remove(gr);
				}
			}
			refreshTable(g);

		}

		public void onFailure(Throwable caught) {
			Window.alert("There was an error: " + caught.toString());
		}
	};

	private AsyncCallback<ResponseObject> cb1 = new AsyncCallback<ResponseObject>() {
		public void onSuccess(ResponseObject res) {
			String code = res.getCode();
			if (!code.equals("0")) {
				Window.alert("There was an error: " + res.getMsg());
				return;
			}
			g.addAll(tmp);
			tmp = null;
			refreshTable(g);

		}

		public void onFailure(Throwable caught) {
			Window.alert("There was an error: " + caught.toString());
		}
	};

	public ServiceRoleRefContent(ServiceMessages cons,
			BifangGWTServiceAsync service, GwtContext context,
			String resourceId, ArrayList<Role> g) {
		this.service = service;
		this.context = context;
		this.cons = cons;
		this.resourceId = resourceId;
		this.g = g;

		panel = new VerticalPanel();
		panel.setSpacing(5);
		panel.setWidth("100%");

		tablePanel = new SimplePanel();
		tablePanel.setWidth("100%");
		panel.add(tablePanel);

		initWidget(panel);

	}

	public void onLoad() {
		if (!loaded) {
			refreshTable(g);

			HorizontalPanel h = new HorizontalPanel();
			Button b = new Button(cons.addRole(), new ClickListener() {
				public void onClick(Widget sender) {
					DialogBox dialogBox = createDialogBox();
					dialogBox.setText(cons.addRole());
					dialogBox.center();
					dialogBox.show();
				}
			});

			Button b1 = new Button(cons.removeRole());
			b1.addClickListener(new ClickListener() {

				public void onClick(Widget sender) {
					RequestObject req = new RequestObject();
					req
							.setAction("han.bifang.gwt.server.action.service.RemoveRolesOfServiceAction");
					ArrayList<String> param = new ArrayList<String>();
					param.add(resourceId);

					for (CustomCheckBox check : checks) {
						if (check.isChecked()) {
							Role gr = (Role) check.getProperties();
							param.add(gr.getId());
						}
					}

					req.setRequest(param);
					service.call(req, cb);

				}

			});

			h.add(b);
			h.add(new HTML("&nbsp;&nbsp;"));
			h.add(b1);

			panel.add(new HTML("&nbsp;"));
			if (PrivilegChecker.hasPrivilege(context, null))
				panel.add(h);
			loaded = true;

		}

	}

	private void refreshTable(List<Role> g) {
		FlexTable table = new FlexTable();
		table.setWidth("60%");
		table.setCellPadding(1);
		table.setCellSpacing(1);
		table.setBorderWidth(1);

		ColumnFormatter cf = table.getColumnFormatter();
		cf.setWidth(0, "10%");
		cf.setWidth(1, "30%");
		cf.setWidth(2, "60%");

		CellFormatter ff = table.getCellFormatter();
		ff.setStyleName(0, 0, "tablecol");
		ff.setStyleName(0, 1, "tablecol");
		ff.setStyleName(0, 2, "tablecol");

		table.setHTML(0, 0, "&nbsp;");
		table.setHTML(0, 1, cons.roleName());
		table.setHTML(0, 2, cons.desc());

		checks = new CustomCheckBox[g.size()];
		for (int i = 0, j = g.size(); i < j; i++) {
			int row = table.getRowCount();
			table.insertRow(row);
			checks[i] = new CustomCheckBox();
			checks[i].setProperties(g.get(i));
			table.setWidget(row, 0, checks[i]);
			table.setHTML(row, 1, g.get(i).getRoleName());
			table.setHTML(row, 2, StringUtils
					.isEmpty(g.get(i).getDescription()) ? "&nbsp;" : g.get(i)
					.getDescription());

		}
		tablePanel.setWidget(table);
	}

	private DialogBox createDialogBox() {
		DialogBox dialogBox = new DialogBox();
		SearchRolePanel gp = new SearchRolePanel(cons, service, dialogBox,
				resourceId);
		gp.setSearcher(this);
		dialogBox.setWidget(gp);

		return dialogBox;
	}

	public void onRoleSearchResult(ArrayList<Role> u) {
		tmp = u;
		RequestObject req = new RequestObject();
		req
				.setAction("han.bifang.gwt.server.action.service.AddRolesOfServiceAction");
		ArrayList<String> param = new ArrayList<String>();
		param.add(resourceId);

		for (Role gg : u) {

			param.add(gg.getId());

		}

		req.setRequest(param);
		service.call(req, cb1);

	}

	public void onUserSearchResult(ArrayList<User> u) {
		// TODO Auto-generated method stub

	}

}
